<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>品牌型号管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- <link rel="stylesheet" href="../web/resource/css/allcss/allCss.css" type="text/css"> -->
</head>
<body>
<div class="query-container">
    <div class="form-row">
        <!-- 品牌名称搜索 -->
        <div class="form-item">
            <label class="form-label">品牌：</label>
            <input type="text"
                   class="form-input"
                   placeholder="请输入品牌名称">
        </div>
        <!-- 状态选择 -->
        <div class="form-item">
            <label class="form-label">状态：</label>
            <select class="form-input form-select-status form-select">
                <option value="">全部</option>
                <option value="1">启用</option>
                <option value="0">停用</option>
            </select>
        </div>
    </div>
    <!-- 操作按钮 -->
    <div class="action-buttons">
        <button class="btn btn-reset">重置</button>
        <button class="btn btn-query">查询</button>
        <button class="btn btn-add">新增</button>
    </div>
</div>
<div class="table-container">
    <table class="data-table">
        <thead class="data-table-thead">
        <tr>
            <th>序号</th>
            <th>品牌名称</th>
            <th>状态</th>
            <th>添加时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<div class="pagination">
    <span>共0条</span>
    <select class="data-table-page" >
        <option value="10" selected>10条/页</option>
        <option value="20">20条/页</option>
        <option value="50">50条/页</option>
    </select>
    <div class="page-num">
        <button class="pre-button">＜</button>
        <span>1</span>
        <button class="next-button">＞</button>
    </div>
</div>

<!-- 新增弹窗 -->
<div class="modal-mask" id="modal-mask-add">
    <div class="modal-content">
        <h3 class="modal-title">
            新增品牌型号
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-add">
            <div class="form-item">
                <label>品牌名称：</label>
                <input type="text" id="add-brandName"
                       placeholder="请输入品牌名称"
                       required>
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">确定</button>
            </div>
        </form>
    </div>
</div>

<!-- 修改弹窗 -->
<div class="modal-mask" id="modal-mask-update">
    <div class="modal-content">
        <h3 class="modal-title">
            修改品牌型号
            <button class="modal-close-btn">×</button>
        </h3>
        <form class="modal-form" id="modal-form-update">
            <div class="form-item">
                <label>品牌名称：</label>
                <input type="text" id="update-brandName" required>
            </div>
            <div class="modal-buttons">
                <button type="button" class="btn-close">关闭</button>
                <button type="submit" class="btn-submit">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    const nextButton = document.querySelector('.next-button');
    const preButton = document.querySelector('.pre-button');
    
    // 渲染表格数据
    function renderTable(data) {
        document.querySelector('.pagination span:first-child')
            .textContent = `共${data.data.total}条`;
        const tbody = document.querySelector('.data-table tbody');

        // 更新页码显示
        document.querySelector('.page-num span').textContent = data.data.current;

        // 处理分页按钮状态
        if (data.data.current >= data.data.pages) {
            nextButton.disabled = true;
            nextButton.style.opacity = "0.5";
        } else {
            nextButton.disabled = false;
            nextButton.style.opacity = "1";
        }

        if (data.data.current <= 1) {
            preButton.disabled = true;
            preButton.style.opacity = "0.5";
        } else {
            preButton.disabled = false;
            preButton.style.opacity = "1";
        }

        tbody.innerHTML = ''; // 清空旧数据
        data.data.records.
        slice( // 根据分页参数切割数据
            (data.data.current - 1)
            * data.data.size,
            data.data.current * data.data.size
        ).forEach((item, index) => {
            const tr = document.createElement('tr');
            const status = item.status === 1 ? '启用' : '停用';
            const buttonText = item.status === 1 ? '停用' : '启用';
            
            tr.innerHTML = `
                <td>${(data.data.current - 1) * data.data.size + index + 1}</td>
                <td>${item.brand || ''}</td>
                <td>${status}</td>
                <td>${item.createTime ? formatDateTime(item.createTime) : '--'}</td>
                <td>
                    <button class="table-disable-btn">${buttonText}</button>
                    <button class="table-edit-btn">修改</button>
                </td>
            `;

            tr.dataset.id = item.id;
            
            const disableBtn = tr.querySelector('.table-disable-btn');
            const editBtn = tr.querySelector('.table-edit-btn');
            
            disableBtn.addEventListener('click', () => toggleStatus(item.id, item.status));
            editBtn.addEventListener('click', () => showUpdateModal(item.id));

            tbody.appendChild(tr);
        });
    }

    // 查询按钮事件
    document.querySelector('.btn-query').addEventListener('click', () => {
        fetchData('query');
    });

    // 重置按钮事件
    document.querySelector('.btn-reset').addEventListener('click', () => {
        document.querySelectorAll('.form-input').forEach(input => {
            if (input.type === 'text') input.value = '';
            if (input.tagName === 'SELECT') input.value = '';
        });
    });

    // 新增按钮事件
    document.querySelector('.btn-add').addEventListener('click', () => {
        document.querySelector('#modal-mask-add').style.display = 'flex';
    });

    // 关闭弹窗
    document.querySelectorAll('.modal-close-btn, .btn-close').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('.modal-mask').style.display = 'none';
        });
    });

    // 获取分页参数
    function getPaginationParams() {
        return {
            page: Math.max(1, parseInt(document.querySelector('.page-num span').textContent)),
            pageSize: parseInt(document.querySelector('.data-table-page').value)
        };
    }

    // 分页按钮事件
    document.querySelector('.pre-button').addEventListener('click', () => {
        fetchData('pre');
    });
    
    document.querySelector('.next-button').addEventListener('click', () => {
        fetchData('next');
    });

    // 数据请求函数
    async function fetchData(type) {
        let { page, pageSize } = getPaginationParams();
        
        if (type === 'pre') {
            page = Math.max(1, page - 1);
        } else if (type === 'next') {
            page += 1;
        }
        
        const queryParams = {
            brand: document.querySelector('input[placeholder="请输入品牌名称"]').value,
            status: document.querySelector('.form-select-status').value,
            page: page,
            rows: pageSize
        };

        try {
            const response = await fetch('http://localhost:8080/sys/customerBrand/pageList', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(queryParams)
            });

            const data = await response.json();
            if (data.status === 0) {
                renderTable(data);
            } else {
                console.error('请求失败:', data.message);
            }
        } catch (error) {
            console.error('请求失败:', error);
        }
    }

    // 页面加载完成后执行初始查询
    document.addEventListener('DOMContentLoaded', () => {
        fetchData('query');
    });

    // 修改状态切换函数
    async function toggleStatus(id, currentStatus) {
        try {
            const newStatus = currentStatus === 1 ? 0 : 1;
            const response = await fetch('http://localhost:8080/sys/customerBrand/disable', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id, status: newStatus })
            });

            const data = await response.json();
            if (data.status === 0) {
                alert(`已${newStatus === 1 ? '启用' : '停用'}`);
                fetchData('query');
            } else {
                alert('状态修改失败：' + (data.message || '未知错误'));
            }
        } catch (err) {
            console.error('状态修改失败:', err);
            alert('状态修改失败：' + err.message);
        }
    }

    // 修改表单提交
    document.getElementById('modal-form-update').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const modal = document.getElementById('modal-mask-update');
        const id = modal.dataset.currentId;
        
        const formData = {
            id: id,
            brand: document.getElementById('update-brandName').value
        };

        try {
            const res = await fetch('http://localhost:8080/sys/customerBrand/update', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const response = await res.json();
            if (response.status === 0) {
                alert('修改成功');
                modal.style.display = 'none';
                fetchData('query'); // 刷新表格数据
            } else {
                alert('修改失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('提交失败:', err);
            alert('提交失败：' + err.message);
        }
    });

    // 修改表单提交
    document.getElementById('modal-form-add').addEventListener('submit', async (e) => {
        e.preventDefault();

        const modal = document.getElementById('modal-mask-add');
        // const id = modal.dataset.currentId;

        const formData = {
            brand: document.getElementById('add-brandName').value
        };

        try {
            const res = await fetch('http://localhost:8080/sys/customerBrand/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const response = await res.json();
            if (response.status === 0) {
                alert('添加成功');
                modal.style.display = 'none';
                fetchData('query'); // 刷新表格数据
            } else {
                alert('添加失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('提交失败:', err);
            alert('提交失败：' + err.message);
        }
    });

    // 显示修改弹窗
    async function showUpdateModal(id) {
        const modal = document.getElementById('modal-mask-update');
        try {
            const res = await fetch(`http://localhost:8080/sys/customerBrand/detail/${id}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            if (!res.ok) {
                throw new Error(`HTTP error! status: ${res.status}`);
            }

            const response = await res.json();
            if (response.status === 0) {
                const data = response.data;
                
                // 填充表单数据
                document.getElementById('update-brandName').value = data.brand || '';
                
                // 存储当前编辑的ID
                modal.dataset.currentId = id;
                modal.style.display = 'flex';
            } else {
                alert('获取详情失败：' + (response.message || '未知错误'));
            }
        } catch (err) {
            console.error('加载详情失败:', err);
            alert(`加载失败: ${err.message}`);
        }
    }
</script>
</body>
</html>